package cn.rokhdelar.umbrsapi.config.annotation;


import cn.rokhdelar.umbrsapi.management.entity.SysUser;
import cn.rokhdelar.umbrsapi.management.repository.SysUserRepo;
import cn.rokhdelar.umbrsapi.management.service.JwtService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;


@Component
public class CurrentUserMethodArgumentResolvers implements HandlerMethodArgumentResolver {

    @Autowired
    private  JwtService jwtService;

    @Autowired
    private  SysUserRepo sysUserRepo;




    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(SysUser.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
    }
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        SysUser userInfo = getLoginUser();
        if (userInfo != null) {
            return userInfo;
        }
        throw new MissingServletRequestPartException("currentUser");
    }


    public static HttpServletRequest getCurrentRequest() {
        HttpServletRequest request = null;
        try {
            RequestAttributes requestAttributes  = RequestContextHolder.getRequestAttributes();
            if (null==requestAttributes){
                return null;
            }
            request = ((ServletRequestAttributes)requestAttributes ).getRequest();
        } catch (Exception e) {
            return request;
        }
        return request;
    }

    public SysUser getLoginUser() {
        HttpServletRequest request = getCurrentRequest();
        String token = request.getHeader("Authorization");
        String username = jwtService.getUsername(token.substring(7));
        // 查询数据库以根据用户名查找对应的 SysUser 对象
        SysUser user = sysUserRepo.findByUsername(username);
        return user;
    }
}
